package intro;

/**
 * 对不同状态的线程发起中断并观察
 * 
 * @author insight
 * @since 2021/8/23
 */
public class InterruptTest {
    public static void main(String[] args) throws InterruptedException {
        Thread st = new Thread(new SleepedThread(), "SleepedThread");
        Thread bt = new Thread(new BusyThread(), "BusyThread");
        
        st.setDaemon(true);
        bt.setDaemon(true);
        st.start();
        bt.start();
        
        // 飞一会
        ThreadUtil.second(2);
        
        // 发起中断
        // 调用了 join wait sleep 处于阻塞时 再发起中断会抛出异常
        // 抛出前会重置中断标志位
        st.interrupt();
        bt.interrupt();

        // 如果线程已终止 即使被中断过 也返回 false
        // interrupted() 也可以获取标志 还会重置标志
        System.out.println("SleepedThread is Interrupted: " + st.isInterrupted());
        System.out.println("BusyThread is Interrupted: " + bt.isInterrupted());

        // 防止守护线程立刻退出
        ThreadUtil.second(2);
    }

    static class SleepedThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                ThreadUtil.second(2);
            }
        }
    }

    static class BusyThread implements Runnable {
        @Override
        public void run() {
            while (true) { }
        }
    }
}